package com.vavr.checkincms.util;

import java.util.Optional;
import com.vavr.checkincms.constant.CheckinConstants;
import com.vavr.checkincms.domain.bo.SystemUserInfoBO;
import com.vavr.checkincms.domain.dto.CheckinUserDTO;
import com.vavr.checkincms.domain.dto.SystemUserInfoDTO;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * CheckinRequestUtils
 *
 * @since 1.0.0
 */
public abstract class CheckinRequestUtils {
    private CheckinRequestUtils() {
        throw new IllegalStateException("Can't Support");
    }

    /**
     * 从会话中获取用户签到信息
     *
     * @return {@link CheckinUserDTO}
     */
    public static Optional<SystemUserInfoDTO> getUserFromRequestAttributes() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        return Optional.ofNullable(
                        requestAttributes.getAttribute(CheckinConstants.CHECKIN_CMS_USER, RequestAttributes.SCOPE_SESSION))
                .map(v -> (SystemUserInfoDTO) v);
    }

    /**
     * 将签到信息放到会话上下文中
     *
     * @param user {@link CheckinUserDTO}
     */
    public static void setUserToRequestAttributes(CheckinUserDTO user) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        requestAttributes.setAttribute(CheckinConstants.CURRENT_USER_V1, user, RequestAttributes.SCOPE_SESSION);
    }

    /**
     * 将登录信息放到会话上下文中
     *
     * @param user {@link SystemUserInfoBO}
     */
    public static void setUserToRequestAttributes(SystemUserInfoDTO user) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        requestAttributes.setAttribute(CheckinConstants.CHECKIN_CMS_USER, user, RequestAttributes.SCOPE_SESSION);
    }
}
